import {Injectable} from '@nestjs/common';
import * as qiniu from 'qiniu';
import {ConfigService} from "@nestjs/config";
import {ResultData} from "../../common/utils/result";
import {AppHttpCode} from "../../common/enums/code.enum";
import * as fs from "node:fs";
import {Readable} from "node:stream";

@Injectable()
export class QiniuService {
    private uploadToken = '';
    private bucket = '';
    private accessKey = '';
    private secretKey = '';
    private domain = '';
    private config:qiniu.conf.Config = null

    constructor(
        private readonly systemConfig: ConfigService,
        ) {
        const accessKey= this.systemConfig.get<string>('app.file.qiniu.accessKey')
        const secretKey= this.systemConfig.get<string>('app.file.qiniu.secretKey')
        const bucket= this.systemConfig.get<string>('app.file.qiniu.bucket')
        const domain= this.systemConfig.get<string>('app.file.qiniu.domain')
        this.accessKey = accessKey;
        this.secretKey = secretKey;
        this.bucket = bucket;
        this.domain = domain;
        this.uploadToken = this.getUploadToken()
        this.config = new qiniu.conf.Config();
    }

    // 获取临时上传凭证，客户端应该在每次上传之前获取上传凭证
    getUploadToken() {
        // 自定义凭证有效期（示例 2 小时，expires 单位为秒，为上传凭证的有效时间）
        const options = this.getUploadTickOptions()
        const mac = new qiniu.auth.digest.Mac(this.accessKey, this.secretKey);
        const putPolicy = new qiniu.rs.PutPolicy(options);
        return putPolicy.uploadToken(mac)
    }
    getUploadTickOptions(){
        return {
            scope: this.bucket,
            expires: 7200,
            returnBody:
                '{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(x:name)"}',
        }
    }
    getFileDownloadUrl(key:string){
        const mac = new qiniu.auth.digest.Mac(this.accessKey, this.secretKey);
        const bucketManager = new qiniu.rs.BucketManager(mac, this.config);
        return bucketManager.publicDownloadUrl(
            this.domain,
            key
        );
    }
    // 服务端直接上传
    async upload(fileName: string, file:Buffer): Promise<any> {
        return new Promise((resolve, reject) => {
            const formUploader = new qiniu.form_up.FormUploader(this.config);
            const putExtra = new qiniu.form_up.PutExtra();
            const uploadToken = this.getUploadToken()
            // console.log(uploadToken,fileName,file,putExtra)
            formUploader
                .put(uploadToken, fileName,file, putExtra)
                .then(async ({ data, resp }) => {
                    if (resp.statusCode === 200) {
                        // console.log(data);
                        const beforeData = data || {};
                        const url = this.getFileDownloadUrl(beforeData.key)
                        resolve({...data,url})
                    } else {
                        console.log(resp.statusCode);
                        console.log(data);
                        reject('上传失败'+resp.statusCode);
                    }
                })
                .catch((err) => {
                    console.log("上传七牛云失败！", err);
                });
        })
    }
    getConfig(){
        const accessKey= this.systemConfig.get<string>('app.file.qiniu.accessKey')
        const secretKey= this.systemConfig.get<string>('app.file.qiniu.secretKey')
        const bucket= this.systemConfig.get<string>('app.file.qiniu.bucket')
        const domain= this.systemConfig.get<string>('app.file.qiniu.domain')
        return {
            accessKey,
            secretKey,
            bucket,
            domain
        }
    }
}